package request

import (
	"backend/pkg/logging"
	"bytes"
	"encoding/json"
	"io/ioutil"
	"net/http"
)

/**
	http get 请求
 */
func Get(url string) string {
	res, err := http.Get(url)
	if err != nil {
		logging.Fatal(err)
	}
	defer res.Body.Close()

	result, err := ioutil.ReadAll(res.Body)
	if err != nil {
		logging.Fatal(err)

		return ""
	}

	return string(result)
}

/**
	post json 请求
 */
func PostJson(url string, params map[string]interface{}) []byte {
	jsonBytes, err := json.Marshal(params)
	if err != nil {
		logging.Fatal(err)
		return []byte("")
	}

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonBytes))
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		logging.Error(err)
		return []byte("")
	}

	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		logging.Error("response status code:" + string(resp.StatusCode))
		return []byte("")
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		logging.Error(err)
		return []byte("")
	}

	return body
}
